<?php

namespace App\Http\Controllers\RBAC;

use App\RBAC\Role;
use App\RBAC\Operation;
use App\RBAC\RoleOperation;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;

class RoleController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $request->session()->put('status', 'current_user:'.Auth::user());
        return view('rbac/role');
    }

    public function apiIndex(Request $request)
    {
        $paginateData=Role::orderBy('id',"ASC")->paginate(intval($request->per_page));
        foreach ($paginateData as $key => $value) {
            $tmp=$value->operations;
        }
        $data['data']=$paginateData;
        $data['operations']=Operation::get();
        return $data;
    }

    public function apiDelete(Request $request,Role $role)
    {
        $operations=$role->operations;
        foreach ($operations as $key => $value) {
            $value->pivot->delete();
        }

        if($role->delete()){
            return ['msg'=>'ok'];
        }else{
            return ['msg'=>'fail'];
        }
    }

    public function apiStore(Request $request)
    {
        if($request->id){
            $group = Role::findOrFail(intval($request->id));
            $group->name=$request->name;
            $group->description=$request->description;
            if($group->save()){
                $group = Role::findOrFail(intval($request->id));
            }
        }else{
            $group = Role::firstOrCreate(['name' => $request->name,'description'=>$request->description]);
        }

        $operations=$request->operations;
        $oldOperations=$request->oldOperations;
        if($request->operations){            
            $role_id=$group->id;
            foreach ($operations as $key => $value) {
                if(!in_array($value,$oldOperations)){
                    RoleOperation::firstOrCreate([
                        'operation_id'=>$value,
                        'role_id'=>$role_id,
                    ]);
                }     
            }
        }
        if($request->oldOperations){            
            $role_id=$group->id;
            foreach ($oldOperations as $key => $value) {
                if(!in_array($value,$operations)){
                    $privilege=RoleOperation::where('operation_id',$value)->where('role_id',$role_id)->first();
                    if($privilege){
                        $privilege->delete();
                    }
                }
            }
        }

        $tmp=$group->operations;

        return $group;
    }
}
